package main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;

import utils.BlockUtils;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(args.length != 3) {
			System.out.println("This command need 3 args");
			System.exit(1);
		}
		String root = args[0];
		String dest1 = args[1];
		String dest2 = args[2];
		root = BlockUtils.prepareRoot(root);
		dest1 = BlockUtils.prepareDest(dest1, root);
		dest2 = BlockUtils.prepareDest(dest2, root);
		File file1 = BlockUtils.checkDestFile(root, dest1);
		if(file1 == null) {
			System.out.println("File doesn't exists in dir " + dest1);
			System.exit(1);
		}
		File file2 = BlockUtils.checkDestFile(root, dest2);
		if(file2 == null) {
			System.out.println("File doesn't exists in dir " + dest2);
			System.exit(1);
		}
		if(compareFiles(file1, file2, root))
			System.out.println("File are equal");
		else
			System.out.println("File aren't equal");
	}
	
	public static boolean compareFiles(File f1, File f2, String root) {
		File file1 = f1;
		File file2 = f2;
		while(file1 != null && file2 != null)
		if (file1.canRead() && file2.canRead()) {
			FileInputStream fin1 = null;
			FileInputStream fin2 = null;
			try {
				fin1 = new FileInputStream(file1);
				fin2 = new FileInputStream(file2);
				long length1 = file1.length();
				long length2 = file2.length();
				byte[] b1 = new byte[(int) length1];
				byte[] b2 = new byte[(int) length2];
				fin1.read(b1);
				fin2.read(b2);
				ByteBuffer wrap1 = ByteBuffer.wrap(b1, BlockUtils.FILESIZEOFFSET, b1.length - BlockUtils.FILESIZEOFFSET);
				int size1 = wrap1.getInt();
				ByteBuffer wrap2 = ByteBuffer.wrap(b2, BlockUtils.FILESIZEOFFSET, b1.length - BlockUtils.FILESIZEOFFSET);
				int size2 = wrap2.getInt();
				if(size1 != size2) 
					return false;
				for(int i = BlockUtils.METADATOFFSET; i < b1.length - 4; i++) {
					if(b1[i] != b2[i])
						return false;
				}
				int nextFile = BlockUtils.getNextFile(b1);
				if(nextFile > 0)
					file1 = BlockUtils.getBlockByNumber(nextFile, root);
				else
					file1 = null;
				nextFile = BlockUtils.getNextFile(b2);
				if(nextFile > 0)
					file2 = BlockUtils.getBlockByNumber(nextFile, root);
				else
					file2 = null;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();	
			} finally {
				try {
					fin1.close();
					fin2.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	        }
		}
		return true;
	}
}
